package com.sensor.Fragment;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Spinner;

import com.landmesure.bluetoothchat.LandCommunicationService;
import com.landmesure.bluetoothchat.R;
import com.landmesure.communication.CommunicationPlatform;
import com.landmesure.communication.ManagerFactory;
import com.landmesure.core.TestMessage;
import com.sensor.Manager.WaterMonitorManager;
import com.sensor.adapter.ListViewAdapter;
import com.sensor.core.DeviceStatus;
import com.sensor.core.HandlerMessage;

import org.json.JSONException;


public class LiveDataFragment extends Fragment {

    public static LandCommunicationService landCommunicationServiceInstance;    //设备管理服务实例

    private WaterMonitorManager waterMonitorManager;
    private Handler handler;
    private Spinner cjkzqSpinner;
    private ArrayAdapter<String> adapter;
    private EditText codEditText;
    private EditText ssEditText;
    private EditText adEditText;
    private EditText zlEditText;
    private LinearLayout linearLayout;
    private View rootView;
    private MyServiceConn mServiceConnection;
    private boolean mIsBind;
    private Context mContext;
    private RadioGroup radioGroup;
    private ListView mListView;
    private ListViewAdapter mAdapter;

    public LiveDataFragment() {

    }

    class MyServiceConn implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder iBinder) {
            LandCommunicationService.MyBinder myBinder;
            myBinder = (LandCommunicationService.MyBinder) iBinder;
            mIsBind = true;
            landCommunicationServiceInstance = myBinder.getInstance();
            landCommunicationServiceInstance.setBaseManager(waterMonitorManager);

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //启动设备管理服务，并绑定它
        mContext = getActivity();
        Intent intent = new Intent(mContext, LandCommunicationService.class);
        mContext.startService(intent);
        mContext.bindService(intent, mServiceConnection = new MyServiceConn(), Context.BIND_AUTO_CREATE);
        handler = new MyHandler();
        CommunicationPlatform.handler = handler;
        waterMonitorManager = (WaterMonitorManager) ManagerFactory.getRealManager("水质监测", handler);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_live_data, container, false);
        radioGroup = rootView.findViewById(R.id.kzms);
        mListView = rootView.findViewById(R.id.listView);
        initView(rootView);
        init();
        initData();
        setListener();
        return rootView;
    }

    private class MyRadioGroupListener implements RadioGroup.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            String value = "01";
            switch (i) {
                case R.id.zd: {
                    value = "00";
                    break;
                }
                case R.id.ts: {
                    value = "01";
                    break;
                }
                case R.id.jx: {
                    value = "02";
                    break;
                }
            }
            try {
                waterMonitorManager.switchControl(waterMonitorManager.cjkzqMap.get(waterMonitorManager.cjkzqList.get(cjkzqSpinner.getSelectedItemPosition())).getInt("ecode"), value);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mIsBind)
            mContext.unbindService(mServiceConnection);
    }

    private class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HandlerMessage.WaterMonitor.GET_CJKZQ_ERROR: {
                    showTip("查询采集控制器失败");
                    break;
                }
                case HandlerMessage.WaterMonitor.GET_INIT_DATAS_SUCCESS: {
                    mAdapter.notifyDataSetChanged();
                    break;
                }
                case HandlerMessage.WaterMonitor.READ_CCD: {
                    Bundle data = msg.getData();
                    TestMessage testMessage = (TestMessage) data.getSerializable("data");
                    if (testMessage != null) {
                        codEditText.setText(testMessage.getValue());
                    }
                    break;
                }
                case HandlerMessage.WaterMonitor.READ_SS: {
                    Bundle data = msg.getData();
                    TestMessage testMessage = (TestMessage) data.getSerializable("data");
                    if (testMessage != null) {
                        ssEditText.setText(testMessage.getValue());
                    }
                    break;
                }
                case HandlerMessage.WaterMonitor.READ_AD: {
                    Bundle data = msg.getData();
                    TestMessage testMessage = (TestMessage) data.getSerializable("data");
                    if (testMessage != null) {
                        adEditText.setText(testMessage.getValue());
                    }
                    break;
                }
                case HandlerMessage.WaterMonitor.READ_ZL: {
                    Bundle data = msg.getData();
                    TestMessage testMessage = (TestMessage) data.getSerializable("data");
                    if (testMessage != null) {
                        zlEditText.setText(testMessage.getValue());
                    }
                    break;
                }
                case HandlerMessage.WaterMonitor.READ_STATUS: {
                    Bundle data = msg.getData();
                    TestMessage testMessage = (TestMessage) data.getSerializable("data");
                    if (testMessage != null) {
                        updateView(testMessage.getEcode(),testMessage.getValue());
                    }
                    break;
                }
            }
        }
    }

    private void updateView(int ecode, String value) {
        for (DeviceStatus deviceStatus : waterMonitorManager.initDatas
        ) {
            if (deviceStatus.getId() == ecode) {
                if (value.equals("0.0"))
                    deviceStatus.setStatus(0);
                else if (value.equals("1.0"))
                    deviceStatus.setStatus(1);
                else
                    deviceStatus.setStatus(2);
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    protected void showTip(String messsage) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext).setTitle("提示")
                .setMessage(messsage);
        builder.create().show();


    }

    //初始化View
    private void initView(View rootView) {
        adapter = new ArrayAdapter<>(getActivity(), R.layout.spinner_item2, R.id.spinner_item_tv2, waterMonitorManager.cjkzqList);
        cjkzqSpinner = rootView.findViewById(R.id.cjkzq);
        codEditText = rootView.findViewById(R.id.et_COD);
        adEditText = rootView.findViewById(R.id.et_AD);
        zlEditText = rootView.findViewById(R.id.et_ZL);
        ssEditText = rootView.findViewById(R.id.et_SS);
        linearLayout = rootView.findViewById(R.id.container);
    }

    private void init() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                waterMonitorManager.serInitDatas(adapter, cjkzqSpinner);
            }
        }).start();


    }

    private void initData() {
        mAdapter = new ListViewAdapter(getActivity(), waterMonitorManager.initDatas);
        mListView.setAdapter(mAdapter);
    }

    private void setListener() {
        radioGroup.setOnCheckedChangeListener(new MyRadioGroupListener());
        cjkzqSpinner.setOnItemSelectedListener(new MySpinnerSelect());
    }

    private class MySpinnerSelect implements android.widget.AdapterView.OnItemSelectedListener {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            onMySpinnerSelect(adapterView, view, i, l);
        }


        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    }

    private void onMySpinnerSelect(AdapterView<?> adapterView, View view, int i, long l) {

        switch (adapterView.getId()) {
            case R.id.cjkzq:
                try {
                    waterMonitorManager.serInitDatas(waterMonitorManager.cjkzqMap.get(waterMonitorManager.cjkzqList.get(i)).getLong("eid"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;

        }
    }

}



